//
//  FGMessageWebViewController.m
//  lite
//
//  Created by feige on 2022/10/12.
//

#import "FGMessageWebViewController.h"
#import <WebKit/WebKit.h>
#import "UIView+FGLayout.h"
#import "UIColor+FGChat.h"

@interface FGMessageWebViewController ()
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
@end

@implementation FGMessageWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // UI
    [self setupSubViews];
    
    // KVO
    [self addObserver];
    
    // data
    [self setupData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.webView.frame = self.view.bounds;
    self.progressView.frame = CGRectMake(0, 0, self.view.mm_w, 1);
}

- (void)dealloc {
    [self removeObserver];
}

#pragma mark - KVO

-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                      context:(void *)context{
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
        && object == self.webView) {
        
        self.progressView.progress = self.webView.estimatedProgress;
        if (_webView.estimatedProgress >= 1.0f) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.progress = 0;
            });
        }
        
    }else if([keyPath isEqualToString:@"title"]
             && object == self.webView){
        self.title = self.title?:change[@"new"];
    }else{
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}

#pragma mark - Private Method

- (void)setupSubViews
{
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
}

- (void)setupData
{
    if (self.url) {
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    } else if (self.htmlString) {
        [self.webView loadHTMLString:self.htmlString baseURL:[NSURL URLWithString:@""]];
    }
}

- (void)addObserver
{
    // 添加监测网页加载进度的观察者
    [self.webView addObserver:self
                   forKeyPath:NSStringFromSelector(@selector(estimatedProgress))
                      options:0
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"title"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    
}

- (void)removeObserver
{
    // 移除观察者
    [_webView removeObserver:self
                  forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    [_webView removeObserver:self
                  forKeyPath:NSStringFromSelector(@selector(title))];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Getter

- (WKWebView *)webView {
    if (!_webView) {
        WKWebViewConfiguration *config = [WKWebViewConfiguration new];
        config.selectionGranularity = YES;
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    }
    return _webView;
}

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectZero];
        _progressView.tintColor = [UIColor fg_colorWithString:@"#558DFF"];
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
}

@end
